#/bin/bash
#解压至/opt/soft/java
if [ ! -d "/opt/soft/java/default" ];then
sudo mkdir -p /opt/soft/java/default
else
sudo rm -rf /opt/soft/java/default/*
fi
if [ ! -e "${HOME}/.${USER}/profile" ]
then
  mkdir ${HOME}/.${USER}
  echo '#!bin/bash' > ${HOME}/.${USER}/profile
fi
if [[ ! -z $1 ]] && [[ -d $1 ]] && [[ -z ${unline_path} ]]
then
PREHOME=$1
elif [[ ! -z ${unline_path} ]]
then
PREHOME=${unline_path}
else
PREHOME=${HOME}"/unline"
fi
#当前脚本所在路径
CURRENTPATH=$(readlink -f "$0")
CUR=`pwd`
echo "当前脚本位置。。。。"${CURRENTPATH}
echo "..."${CUR}
DIR=$( dirname "$(readlink -f  ${BASH_SOURCE[0]})" )
echo ${DIR}
#当前脚本上一层路径
PARENTPATH=$(dirname ${DIR})
SOURCEFILE=`sh ${PARENTPATH}/getunlinefile.sh ${PREHOME} java`
sudo tar -zxvf ${PREHOME}/java/${SOURCEFILE} -C /opt/soft/java/default --strip-components=1
grep -q 'export JAVA_DEFAULT_HOME=/opt/soft/java/default' ~/.${USER}/profile
if [ $? -eq 1 ];then
sudo sed -i'' '$aexport JAVA_DEFAULT_HOME=/opt/soft/java/default' ~/.${USER}/profile
sudo sed -i'' '$aif [[ -z $JAVA_HOME ]];then\necho "set default jdk ${JAVA_DEFAULT_HOME}"\nexport JAVA_HOME=${JAVA_DEFAULT_HOME}\nfi' ~/.${USER}/profile
fi
grep -q 'export JRE_HOME=${JAVA_HOME}/jre' ~/.${USER}/profile
if [ $? -eq 1 ];then
sudo sed -i'' '$aexport JRE_HOME=${JAVA_HOME}/jre' ~/.${USER}/profile
fi
grep -q 'export CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib' ~/.${USER}/profile
if [ $? -eq 1 ];then
sudo sed -i'' '$aexport CLASSPATH=.:${JAVA_HOME}/lib:${JRE_HOME}/lib' ~/.${USER}/profile
fi
grep -q 'export PATH=${JAVA_HOME}/bin:${PATH}' ~/.${USER}/profile
if [ $? -eq 1 ];then
sudo sed -i'' '$aexport PATH=${JAVA_HOME}/bin:${PATH}:${HOME}/.local/bin' ~/.${USER}/profile
fi
#刷新环境变量
grep -q 'source '"${HOME}"'/.'"${USER}"'/profile' ~/.zshrc
if [ $? -eq 1 ];then
sudo sed -i'' '$asource '"${HOME}"'/.'"${USER}"'/profile' ~/.zshrc
fi

# install other jdk by alias
alias_floders=`ls -lt ${PREHOME}/java | grep ^d | awk '{print $NF}'`
for alias in ${alias_floders}
do
  ALIASSOURCEFILE=`sh ${PARENTPATH}/getunlinefile.sh ${PREHOME} java/${alias}`
  sh ${DIR}/installjava.sh -f ${PREHOME}/java/${alias}/${ALIASSOURCEFILE} -a ${alias} -F true
done
sudo source ~/.zshrc
